package com.yanliang.utils;

import com.yanliang.model.MyContext;
import com.yanliang.model.MyHost;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * @author yanliang
 * @date 5/10/20202:49 PM
 */
public class StaticResourceUtil {
	/**
	 * 获取静态资源文件的绝对路径
	 * @param path
	 * @return
	 */
	public static String getAbsolutePath(String path) {
		String absolutePath = StaticResourceUtil.class.getResource("/").getPath();
		return absolutePath.replaceAll("\\\\","/") + path;
	}


	/**
	 * 读取静态资源文件输入流，通过输出流输出
	 */
	public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {

		int count = 0;
		while(count == 0) {
			count = inputStream.available();
		}

		int resourceSize = count;
		// 输出http请求头,然后再输出具体内容
		outputStream.write(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes());

		// 读取内容输出
		long written = 0 ;// 已经读取的内容长度
		int byteSize = 1024; // 计划每次缓冲的长度
		byte[] bytes = new byte[byteSize];

		while(written < resourceSize) {
			if(written  + byteSize > resourceSize) {  // 说明剩余未读取大小不足一个1024长度，那就按真实长度处理
				byteSize = (int) (resourceSize - written);  // 剩余的文件内容长度
				bytes = new byte[byteSize];
			}

			inputStream.read(bytes);
			outputStream.write(bytes);

			outputStream.flush();
			written+=byteSize;
		}
	}

	/**
	 * 根据url和映射实体对象获得上下文内容对象
	 *
	 * @param url    url
	 * @param hostList 映射实体对象
	 * @return
	 */
	public static MyContext getContext(String url, List<MyHost> hostList) {
		//1.根据请求路径的主机名匹配主机实例对象
		if (hostList == null || hostList.isEmpty()) {
			return null;
		}
		for (MyHost host : hostList) {
			List<MyContext> contextList = host.getContexts();
			//2.匹配中请求路径的项目名匹配Context并返回
			if (contextList == null || contextList.isEmpty()) {
				return null;
			}
			for (MyContext context : contextList) {
				if (context.getName().equals(url.split("/")[1])) {
					return context;
				}
			}
		}
		return null;
	}


}
